const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
require('dotenv').config();

const { connectDB } = require('./config/database');
const productRoutes = require('./routes/product');
const configRoutes = require('./routes/config');
const docsRoutes = require('./routes/docs');

// 引入模型以确保关联关系被建立
const Product = require('./models/Product');
const ProductVideo = require('./models/ProductVideo');

// 建立模型关联关系
Product.hasMany(ProductVideo, {
  foreignKey: 'product_id',
  sourceKey: 'id',
  as: 'videos',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});

ProductVideo.belongsTo(Product, {
  foreignKey: 'product_id',
  targetKey: 'id',
  as: 'product',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});

const app = new Koa();
const router = new Router();

// 连接数据库
connectDB();

// 中间件
app.use(cors());
app.use(bodyParser());

// 路由
app.use(productRoutes.routes());
app.use(productRoutes.allowedMethods());
app.use(configRoutes.routes());
app.use(configRoutes.allowedMethods());
app.use(docsRoutes.routes());
app.use(docsRoutes.allowedMethods());

// 错误处理
app.on('error', (err, ctx) => {
  console.error('服务器错误:', err);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;